import doT from '../../../../vendor/template/doT.js';
import { requestFilePath } from '../../../common/api/file-request.js';
import watermark from '../../../common/watermark.js';
import InboundPlanApi from '../../../common/api/breed/inboundplan.api.js';
import { DictionaryType, requestDict } from '../../../common/dictionary/dictionary-type.js';

(function (window, document, $) {
    let _speLevelList,
        listindex = '';
    let inboundPlanPlaceInfo = {};
    // 获取参数
    const _json = Utils.ParsingUrl(window.location);
    const lksalesmainTemplate = doT.template($('#looksalesplanmain-template').text());
    const addPlaceTypeTemplate = doT.template($('#addPlaceType-template').text());

    $(function () {
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
        _watermarkBgImg();
        _initCommand();
    });

    //返回列表
    $(document).on('click', '#returnlist', function () {
        location.href = `./inboundplanlist.html`;
    });

    //命令初始化
    const _initCommand = async () => {
        let ids = getUrlKey('id');
        // 入厂计划场所类型
        await requestDict(DictionaryType.INBOUNDPLANPLACE_TYPE).then((res) => {
            res.data.forEach((item) => {
                inboundPlanPlaceInfo[item.value] = item.displayName;
            });
        });
        InboundPlanApi.getDetailPerInPlan(ids).then((result) => {
            let placeType = result.person?.placeType || '';
            let placeTypeList = [],
                placeTypeNameList = [];
            if (placeType) {
                if (placeType.includes(',')) {
                    placeTypeList = placeType.split(',');
                } else {
                    placeTypeList = [placeType];
                }
            }
            placeTypeList.forEach((s) => {
                let str = Utils.IsNotNull(inboundPlanPlaceInfo[s]) ? inboundPlanPlaceInfo[s] : s || '';
                if (str) {
                    placeTypeNameList.push(str);
                }
            });
            result.placeTypeNameList = placeTypeNameList.join(',');
            $('#looksalesMain').empty().append(lksalesmainTemplate(result));

            if (Utils.IsNotNull(result.person.attachments)) {
                _viewImages(result.person.attachments, `uploaderFiles`);
            }

            $('#belongingsDiv').empty().append(addPlaceTypeTemplate(result.person.belongings));
        });
    };

    /** 获取地址栏的 参数  传入 字段返回值 */
    const getUrlKey = (name) => {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]);
        return null;
    };

    // 添加水印信息
    const _watermarkBgImg = () => {
        let _userInfo = JSON.parse(Utils.GetSessionStorage('SNAccountEply')) || {};
        watermark.set(_userInfo.name + _userInfo.numCode); // 水印
    };

    // 附件回显
    const _viewImages = async (images, id) => {
        let _imag = images.split(',');
        if (_imag) {
            let _sun = 0;
            for (let i = 0; i < _imag.length; i++) {
                ++_sun;
                if (Utils.IsNotNull(_imag[i]) && _imag[i] != 'string') {
                    setTimeout(async () => {
                        await requestFilePath(_imag[i]).then((_res) => {
                            if (_res.isSucceed) {
                                let _li;
                                if (['jpg', 'jpeg', 'png', 'gif'].indexOf(_imag[i].suffix) < 0) {
                                    _li = `<li class="weui-uploader__file"  data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                                } else {
                                    _li = `<li class="weui-uploader__file" data-id="${_sun}" data-url="${_res.data}" data-image-id="${_imag[i]}" style="background-image: url(${_res.data}) "></li>`;
                                }
                                $(`#${id}`).append(_li);
                            }
                        });
                    }, 200);
                }
            }
            if (_sun == 20) {
                $('.weui-uploader__input-box').hide();
            }
        }
        $(document).on('click', `#${id}`, function (e) {
            let target = e.target;
            while (!target.classList.contains(`weui-uploader__file`) && target) {
                target = target.parentNode;
            }
            if (!target) return;
            //从图片对应的li标签中获得所需属性
            let gallery = weui.gallery($(target).attr('data-url'), {
                className: 'custom-name',
            });
            $('.weui-icon_gallery-delete').css('display', 'none');
        });
    };
})(window, document, jQuery);
